import urllib2
import urlparse
import json
from odoo import exceptions

class HttpExporter:
    ptengine_export_enable = 'ptengine.export.export_enable'
    ptengine_export_endpoint = 'ptengine.export.endpoint'

    def __init__(self, config):
        if not config.get_param(HttpExporter.ptengine_export_enable) == 'True':
            self.exportEnabled = False
            return

        self.serverEndpoint = config.get_param(HttpExporter.ptengine_export_endpoint)
        self.exportEnabled = True

    def Export(self, model, vals):
        if not self.exportEnabled:
            return False

        resource, exportObject = model.getExportInfo(vals)

        if len(exportObject) == 0:
            return False

        print exportObject
        url = urlparse.urljoin(self.serverEndpoint, resource)
        response = HttpExporter.PostData(url, json.dumps(exportObject))
        result = json.loads(response)
        print result
        if result and result.has_key('status'):
            if result['status'] == 'success':
                return True
            else:
                raise exceptions.Warning(result['message'])
        else:
            raise exceptions.Warning('Something wrong with PtConsole')

    @staticmethod
    def PostData(url, object):
        try:
            request = urllib2.Request(url, data=object, headers={'Content-type': 'application/json'})
            binary =  urllib2.urlopen(request)
            return binary.read()
        except urllib2.HTTPError:
            raise Exception("Can't connect to PtConsole")